﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using UserSettings_Update_Silverlight.CrmSdk;

namespace UserSettings_Update_Silverlight
{

    public partial class MainPage : UserControl
    {
        int _MaxRecordsToReturn = 24;
        int _PageNumber = 1;
        string _PagingCoockie = string.Empty;
        QueryExpression query;

        List<UserSettings> userSettingsCollection = new List<UserSettings>();
        public MainPage(App app)
        {
            InitializeComponent();
            app.UnhandledException += new EventHandler<ApplicationUnhandledExceptionEventArgs>(app_UnhandledException);

            query = new QueryExpression()
            {
                EntityName = "systemuser",
                ColumnSet = new ColumnSet()
                {
                    Columns = new System.Collections.ObjectModel.ObservableCollection<string>(new string[] { "fullname", "domainname" })

                },
                Orders = new System.Collections.ObjectModel.ObservableCollection<OrderExpression>(new OrderExpression[]
                    {
                        new OrderExpression() { AttributeName = "fullname", OrderType = OrderType.Ascending }
                    })
            };

            LinkEntity le = new LinkEntity();
            le.LinkFromEntityName = "systemuser";
            le.LinkFromAttributeName = "systemuserid";
            le.LinkToEntityName = "usersettings";
            le.LinkToAttributeName = "systemuserid";
            le.EntityAlias = "UserSettings";
            le.Columns = new ColumnSet();
            le.Columns.Columns = new System.Collections.ObjectModel.ObservableCollection<string>(new string[] { "homepagearea", "homepagesubarea", "paginglimit", "defaultcalendarview", "timeformatstring", "getstartedpanecontentenabled" });
            query.LinkEntities = new ObservableCollection<LinkEntity>();
            query.LinkEntities.Add(le);

            query.ColumnSet = new ColumnSet();
            query.ColumnSet.AllColumns = true;

        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            try
            {
                query.PageInfo = new PagingInfo { Count = _MaxRecordsToReturn, PageNumber = _PageNumber, PagingCookie = null };
                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query;
                IOrganizationService service = SilverlightUtility.GetSoapService();
                service.BeginExecute(request, new AsyncCallback(UserSettignsList_ClickCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void ReportError(Exception ex)
        {
            this.ReportMessage("Exception: " + SilverlightUtility.ConvertToString(ex));
        }

        private void ReportMessage(string message)
        {
            this.Dispatcher.BeginInvoke(() => MessageBox.Show(message));
        }

        private void app_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
        {
            this.ReportError(e.ExceptionObject);
        }

        private void AccountList_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                query.PageInfo = new PagingInfo { Count = _MaxRecordsToReturn, PageNumber = _PageNumber, PagingCookie = null };
                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query;
                IOrganizationService service = SilverlightUtility.GetSoapService();
                service.BeginExecute(request, new AsyncCallback(UserSettignsList_ClickCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void UserSettignsList_ClickCallback(IAsyncResult result)
        {
            try
            {
                OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);

                EntityCollection results = (EntityCollection)response["EntityCollection"];
                _PagingCoockie = results.PagingCookie;

                if (results.Entities.Count == 0)
                {

                }
                userSettingsCollection = new List<UserSettings>();
                if (results.MoreRecords)
                {
                    this.Dispatcher.BeginInvoke(() => Next.IsEnabled = true);
                }
                else
                {
                    this.Dispatcher.BeginInvoke(() => Next.IsEnabled = false);
                }

                //If _PageNumber is 1 Disable Previous Nav Button.
                if (_PageNumber == 1)
                {
                    this.Dispatcher.BeginInvoke(() => Previous.IsEnabled = false);
                }
                else
                {
                    this.Dispatcher.BeginInvoke(() => Previous.IsEnabled = true);
                }

                FillUserSettings(results);
                this.Dispatcher.BeginInvoke(() => userSettingsGrid.ItemsSource = userSettingsCollection);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void FillUserSettings(EntityCollection collections)
        {
            if (collections.Entities.Count > 0)
            {
                userSettingsCollection = new List<UserSettings>();
            }

            foreach (Entity entity in collections.Entities)
            {
                UserSettings us = new UserSettings();
                us.SystemUserId = entity.Id;
                us.FullName = entity.GetAttributeValue<string>("fullname");
                us.DomainName = entity.GetAttributeValue<string>("domainname");
                us.HomepageArea = entity.GetAttributeValue<AliasedValue>("UserSettings.homepagearea").Value.ToString();
                us.HomepageSubarea = entity.GetAttributeValue<AliasedValue>("UserSettings.homepagesubarea").Value.ToString();
                us.PagingLimit = (int)entity.GetAttributeValue<AliasedValue>("UserSettings.paginglimit").Value;

                if ((int)entity.GetAttributeValue<AliasedValue>("UserSettings.defaultcalendarview").Value == 0)
                {
                    us.DefaultCalendarView = "Day";
                }
                else if ((int)entity.GetAttributeValue<AliasedValue>("UserSettings.defaultcalendarview").Value == 1)
                {
                    us.DefaultCalendarView = "Week";
                }
                else if ((int)entity.GetAttributeValue<AliasedValue>("UserSettings.defaultcalendarview").Value == 2)
                {
                    us.DefaultCalendarView = "Month";
                }

                us.TimeFormatString = entity.GetAttributeValue<AliasedValue>("UserSettings.timeformatstring").Value.ToString();
                us.GetStartedPaneContentEnabled = (bool)entity.GetAttributeValue<AliasedValue>("UserSettings.getstartedpanecontentenabled").Value;

                userSettingsCollection.Add(us);
            }

        }

        private void Save_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                List<UserSettings> list = (List<UserSettings>)userSettingsGrid.ItemsSource;

                foreach (UserSettings u in list)
                {
                    UpdateUserSettigns(u);
                    SaveBtn.IsEnabled = false;
                }
            }
            catch (Exception ex)
            { this.ReportError(ex); }
        }

        private void UpdateUserSettigns(UserSettings userSettings)
        {
            Entity e = new Entity();

            e.LogicalName = "usersettings";

            e["systemuserid"] = userSettings.SystemUserId;

            e["paginglimit"] = userSettings.PagingLimit;

            if (string.Compare(userSettings.DefaultCalendarView, "Day") == 0)
            {
                e["defaultcalendarview"] = 0;
            }
            else if (string.Compare(userSettings.DefaultCalendarView, "Week") == 0)
            {
                e["defaultcalendarview"] = 1;
            }
            else if (string.Compare(userSettings.DefaultCalendarView, "Month") == 0)
            {
                e["defaultcalendarview"] = 2;
            }

            e["getstartedpanecontentenabled"] = userSettings.GetStartedPaneContentEnabled;

            try
            {
                IOrganizationService service = SilverlightUtility.GetSoapService();

                service.BeginUpdate(e, new AsyncCallback(EntityUpdate_AsyncCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void EntityUpdate_AsyncCallback(IAsyncResult result)
        {
            ((IOrganizationService)result.AsyncState).EndUpdate(result);

            this.Dispatcher.BeginInvoke(() => SaveBtn.IsEnabled = true);
        }
        private void EntityList_ClickCallback(IAsyncResult result)
        {
            try
            {
                OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void Previous_Click(object sender, RoutedEventArgs e)
        {
            _PageNumber--;
            try
            {
                query.PageInfo = new PagingInfo { Count = _MaxRecordsToReturn, PageNumber = _PageNumber, PagingCookie = _PagingCoockie };
                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query;
                IOrganizationService service = SilverlightUtility.GetSoapService();
                service.BeginExecute(request, new AsyncCallback(UserSettignsList_ClickCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void Next_Click(object sender, RoutedEventArgs e)
        {
            _PageNumber++;
            try
            {
                query.PageInfo = new PagingInfo { Count = _MaxRecordsToReturn, PageNumber = _PageNumber, PagingCookie = _PagingCoockie };
                OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                request["Query"] = query;
                IOrganizationService service = SilverlightUtility.GetSoapService();
                service.BeginExecute(request, new AsyncCallback(UserSettignsList_ClickCallback), service);
            }
            catch (Exception ex)
            {
                this.ReportError(ex);
            }
        }

        private void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            ((ComboBox)sender).IsDropDownOpen = true;
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserSettings pr = (UserSettings)userSettingsGrid.SelectedItem;
            pr.HomepageArea = ((Unit)((ComboBox)sender).SelectedItem).Nm;

        }

        private void ComboBoxCalendarView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            UserSettings pr = (UserSettings)userSettingsGrid.SelectedItem;
            pr.DefaultCalendarView = ((ComboBoxItem)((ComboBox)sender).SelectedItem).Content.ToString();
        }

        private void Search_Click(object sender, RoutedEventArgs e)
        {
            if (SearchTxt.Text.Trim().Length > 0)
            {
                ConditionExpression cond = new ConditionExpression();
                cond.AttributeName = "fullname";
                cond.Operator = ConditionOperator.Like;
                cond.Values = new ObservableCollection<object>(new string[] { "%" + SearchTxt.Text + "%" });

                FilterExpression filter = new FilterExpression();
                filter.Conditions = new ObservableCollection<ConditionExpression>();
                filter.Conditions.Add(cond);
                filter.FilterOperator = LogicalOperator.And;

                _PageNumber = 1;
                _PagingCoockie = null;
                try
                {
                    query.Criteria = filter;
                    query.PageInfo = new PagingInfo { Count = _MaxRecordsToReturn, PageNumber = _PageNumber, PagingCookie = _PagingCoockie };
                    OrganizationRequest request = new OrganizationRequest() { RequestName = "RetrieveMultiple" };
                    request["Query"] = query;

                    IOrganizationService service = SilverlightUtility.GetSoapService();
                    service.BeginExecute(request, new AsyncCallback(UserSettignsList_ClickCallback), service);
                }
                catch (Exception ex)
                {
                    this.ReportError(ex);
                }
            }
            else
            {
                ReportMessage("Enter Search Text");
            }
        }

        private void dataPager_PageIndexChanged(object sender, EventArgs e)
        {

        }
    }

    public class UnitProvider
    {
        public List<Unit> UnitList
        {
            get
            {
                return new List<Unit> { new Unit(1, "Workplace"), 
                                        new Unit(2, "Partner") ,
                                        new Unit(3, "Sales"),
                                        new Unit(4, "Marketing"),
                                        new Unit(5, "Research"),
                                        new Unit(6, "Subsidiary")};
            }
        }
    }

    public class Unit
    {
        Int32 _code = 0;
        string _nm = string.Empty;

        public Unit(Int32 pCode, string pNm)
        {
            _code = pCode;
            _nm = pNm;
        }
        public Int32 Code
        {
            get { return _code; }
            set { _code = value; }
        }

        public string Nm
        {
            get { return _nm; }
            set { _nm = value; }
        }
    }

    public class UserSettings
    {
        private int _PagingLimit = 0;

        public Guid SystemUserId { get; set; }
        public string FullName { get; set; }
        public string DomainName { get; set; }
        public string HomepageArea { get; set; }
        public string HomepageSubarea { get; set; }
        public string DefaultCalendarView { get; set; }
        public string CurrencySymbol { get; set; }
        public int PagingLimit
        {
            get { return _PagingLimit; }
            set
            {
                if (value > 250)
                {
                    throw new ArgumentException("Paging limit cannot be more than 250");
                }
                else if (value < 10)
                {
                    throw new ArgumentException("Paging limit cannot be less than 10");
                }
                else
                {
                    _PagingLimit = value;
                }
            }
        }
        public string TimeFormatString { get; set; }
        public string WorkdayStartTime { get; set; }
        public string WorkdayStopTime { get; set; }
        public bool GetStartedPaneContentEnabled { get; set; }
    }

}